const mysql = require('mysql');
const dbConfig = require('../config/database');
const config = require('../config');

class DatabaseManager {
  constructor() {
    this.pools = {};
  }

  getPool(country) {
    const countryCode = config.countries[country];
    if (!countryCode) {
      throw new Error(`Invalid country code: ${country}`);
    }

    if (!this.pools[countryCode]) {
      const dbSettings = dbConfig[countryCode];
      if (!dbSettings) {
        throw new Error(`No database configuration found for country: ${countryCode}`);
      }
      this.pools[countryCode] = mysql.createPool(dbSettings);
    }
    return this.pools[countryCode];
  }

  async query(country, sql, params = []) {
    return new Promise((resolve, reject) => {
      const pool = this.getPool(country);
      pool.getConnection((err, connection) => {
        if (err) {
          reject(err);
          return;
        }

        connection.query(sql, params, (error, results) => {
          connection.release();
          if (error) {
            reject(error);
            return;
          }
          resolve(results);
        });
      });
    });
  }
}

module.exports = new DatabaseManager(); 